/**
 * 
 */
package com.csc.bankingsystem.web.spring.security;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.csc.bankingsystem.core.dto.BSAuthReturnObject;
import com.csc.bankingsystem.core.entity.UserInfo;
import com.csc.bankingsystem.core.service.UserInfoService;
import com.csc.bankingsystem.core.util.ConstantManager;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author angelkid
 *
 */
public class AuthSuccessHandler extends
		SavedRequestAwareAuthenticationSuccessHandler {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(AuthSuccessHandler.class);

	private final ObjectMapper mapper;

	@Autowired
	AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) {
		this.mapper = messageConverter.getObjectMapper();
	}
	
	@Autowired
	private UserInfoService userInfoService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		response.setStatus(HttpServletResponse.SC_OK);
		SecurityContextHolder.getContext().getAuthentication();
		BSUsernamePasswordAuthenticationToken bankingsystemAuth = (BSUsernamePasswordAuthenticationToken) authentication;
		String username = (String) bankingsystemAuth.getPrincipal();
		UserInfo userInfo = userInfoService.getUserInfoByLoginId(username);
		request.getSession().setAttribute(ConstantManager.CURRENT_USER_ID, userInfo.getId());
		String token = bankingsystemAuth.getToken();
		LOGGER.info(username + " got is connected ");
		BSAuthReturnObject returnObj = new BSAuthReturnObject();
		returnObj.setToken(token);
		returnObj.setLoginId(username);
		PrintWriter writer = response.getWriter();
		mapper.writeValue(writer, returnObj);
		writer.flush();
	}
}
